<?php
declare (strict_types = 1);
namespace app\api\controller;

use think\Exception;
use app\api\controller\BaseController;
use service\JsonService as Json;
use think\exception\ValidateException;

use think\facade\{Db, Log, Cache};

use app\common\model\User;
use app\common\model\UserResume as Resume;
use app\common\model\CheckRule;
use app\common\validate\{UserValidate};

class WxLoginController extends BaseController
{
    /** 
     * 获取openid
     */
    public function getOpenId()
    {
        $data      = input('');
        $appid     = config('api.wx.appid');
        $appsecret = config('api.wx.appsecret');

        $url = "https://api.weixin.qq.com/sns/jscode2session?appid={$appid}&secret={$appsecret}&js_code={$data['wxcode']}&grant_type=authorization_code";
        $res = curl_get($url);
        $res = json_decode($res, TRUE);

        if(isset($res['errcode'])) return Json::fail($res['errmsg']);
        return Json::success('ok', $res);
    }

    /**
     * 微信登录
     */
    public function login()
    {
        $param = input('');
        Log::write($param);

        try{
            validate(UserValidate::class)->scene('wxlogin')->check($param);
        }catch(ValidateException $e){
            $this->error_back($e->getError());
        }

        $userInfo = User::getFind(['openid' => $param['openid']]);

        self::beginTrans();
        try{
            if($userInfo === false){
                $flag = User::add([
                    'name'    => $param['name'],
                    'avatars' => $param['avatars'],
                    'openid'  => $param['openid'],
                ]);
            
                if($flag === false) throw new Exception('注册失败！');

                $token = $this->jwt($flag['id']);
                User::editWhere(['token' => $token], ['openid' => $param['openid']]);
                Resume::add(['user_id' => $flag['id']]);
            }else{
                User::edit(['id' => $userInfo['id'], 'avatars' => $param['avatars']]);
                $token = $userInfo['token'];
            }

            self::commitTrans();
        }catch (Exception $e){
            self::rollbackTrans();
            return Json::fail('登录失败，请稍后重试，错误码：'.$e->getMessage());
        }

        if($userInfo['check_clock_id'] != 0){
            $checkRuleInfo = CheckRule::getFind(['id' => $userInfo['check_clock_id']]);

            if($checkRuleInfo === false){
                $clockRule = [];
            }else{
                $clockRule['name']       = $checkRuleInfo['name'];
                $clockRule['start_time'] = secondToHour($checkRuleInfo['start_time']);
                $clockRule['end_time']   = secondToHour($checkRuleInfo['end_time']);
            }
        }else{
            $clockRule = [];
        }

        $backData = [
            'token'      => $token,
            'clock_rule' => $clockRule,
            'staff_no'   => $userInfo['staff_no'],
        ];

        $info['clock_rule'] = $clockRule;

        return Json::success('登录成功', $backData);
    }

    /** 微信信息解密 */
    public function decrypt()
    {
        $param = input('');

        try{
            validate(UserValidate::class)->scene('decrypt')->check($param);
        }catch(ValidateException $e){
            return Json::fail($e->getError());
        }

        $object = new \wxdecrypt\WXBizDataCrypt(config('api.wx.appid'), $param['session_key']);
        $errCode = $object->decryptData($param['encrypted_data'], $param['iv'], $datas);

        if($errCode !== 0) return Json::fail('解密失败，errCode:'.$errCode);
        return Json::success('解密成功', $datas);
    }

    /**
     * 用户是否授权
     */
    public function isAuth()
    {
        return Json::success('ok', User::isAuth($this->user_id));
    }

    /** 查询微信小程序二维码 */
    public function codeunlimit()
    {
        $access_token = $this->getaccesstoken();
        $data = input('post.');

        try{
            validate(UserValidate::class)->scene('codeunlimit')->check($data);
        }catch(ValidateException $e){
            $this->error_back($e->getError());
        }

        $url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token={$access_token}";

        $post_data = [
            'scene' => $data['scene'],
            'page'  => $data['page'],
        ];

        $post_json = json_encode($post_data);
        $result = curl_post($url, $post_json);

        if(json_decode($result, true)){
            $result = json_decode($result, true);
            $this->error_back(['code' => $result['errcode'], 'msg' => $result['errmsg']]);
        } else {
            $jpg = $result;
            // $url = Env::get("root_path") . "/public";
            $url = root_path() . "/public";
            $file_name = "/storage/wxcode/" . md5(date('YmdHis').rand(000, 999)).".jpg";
            $file = fopen($url . $file_name, "w");
            fwrite($file, $jpg);
            fclose($file);
            $this->success_back('查询成功', ['url' => $file_name]);
        } 
    }

    /** 获取access_token（小程序） */
    private function getaccesstoken()
    {
        $system = getSystem();

        $access_token = Cache::get('wx_access_token:' . $system['appid']);

        if($access_token){
            return $access_token;
        }else{
            //1.请求url地址
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$system['appid']}&secret={$system['appsecret']}";
            $res = curl_get($url);
            $res = json_decode($res, true);

            if(isset($res['errcode']) && $res['errcode']!=0){
                Log::write('AccessTokenError,ErrCode:'.$res['errcode'].',ErrMsg:'.$res['errmsg']);
            }

            $access_token = $res['access_token'];
            Cache::tag('accessToken')->set('wx_access_token:' .  $system['appid'], $access_token, 3600);

            return $access_token;
        }  
    }
}